package Hot100.Medium.LinkedList;

public class LC160_GetIntersectionNode {
    public static void main(String[] args) {

    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB){
        // 探测长度，如果B长则跟A交换，方便操作
        ListNode curA = headA;
        ListNode curB = headB;
        int lenA=0,lenB=0;
        while(curA != null){
            lenA++;
            curA = curA.next;
        }
        while(curB!=null){
            lenB++;
            curB=curB.next;
        }
        curA = headA;
        curB = headB;
        if(lenA < lenB){
            int temp = lenA;
            lenA = lenB;
            lenB = temp;
            ListNode tempNode=curA;
            curA=curB;
            curB=tempNode;
        }
        // 现在让指针从同一位置开始往后移动，什么时候指向同一节点，什么时候就是相交节点
        int diffLen = lenA - lenB;
        for(int i = 0; i < diffLen; i++){
            curA = curA.next;
        }
        for(int j = 0; j < lenB; j++){
            if(curA == curB){
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }

}
